/*************************************************************************
> File Name: linklist.c
> Author: hzy
> Created Time: 2023-07-29 10:42:47
> Description:
************************************************************************/
#include "linklist.h"

node_t *CreateLinkList(void)
{
    // 创建头结点存储空间
    node_t *head = malloc(sizeof(node_t));
    if (head == NULL)
    {
        return NULL;
    }
    // 设置结点成员初始值
    memset(head, 0, sizeof(node_t));
    head->pre = head;
    head->next = head;

    return head;
}

int InserLinkList(node_t *head, int local, int my_id, char *my_name, int my_age)
{
    int i = 0;
    node_t *p = head;

    // 判断插入位置是否满足条件：local >= 0
    if (local < 0)
        return -1;

    // 找到需要插入结点的前一个结点
    for (i = 0; i < local; i++)
    {
        p = p->next;
        if (p == head)
        {
            return -1;
        }
    }
    // //
    // for (i = 0; i < local; i++)
    // {
    //     p = p->pre;
    //     if (p == head)
    //     {
    //         return -1;
    //     }
    // }

    // 创建需要插入数据结点空间
    node_t *q = malloc(sizeof(node_t));
    if (q == NULL)
    {
        return -1;
    }
    memset(q, 0, sizeof(node_t));

    // 插入结点
    q->pre = p;
    p->next->pre = q;
    q->next = p->next;
    p->next = q;

    q->data.id = my_id;
    strcpy(q->data.name, my_name);
    q->data.age = my_age;

    return 0;
}

void DisplayLinklist(node_t *head)
{
    node_t *p = head->next;

    while (p != head)
    {
        printf("ID:%-6d ", p->data.id);
        printf("姓名:%-4s ", p->data.name);
        printf("年龄:%-2d", p->data.age);
        p = p->next;
        printf("\n");
    }
    
}
